package com.topscomm.main.config;

import com.topscomm.basic.util.Config;
import com.topscomm.pub.util.SecurityUtil;
import lombok.Data;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.RetryNTimes;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.Primary;
import org.springframework.core.annotation.Order;

/**
 * curator连接zookeeper客户端
 *
 * @description:
 * @author: donghang
 * @date: 2020年7月13日下午6:20:00
 * @modify:
 */
@Data
public class LocalZookeeperCuratorConfig extends ZookeeperCuratorConfig {
	@Value("${curator.retryCount}")
	private int retryCount;

	@Value("${curator.elapsedTimeMs}")
	private int elapsedTimeMs;

	@Value("${curator.connectString}")
	private String connectString;

	@Value("${curator.sessionTimeoutMs}")
	private int sessionTimeoutMs;

	@Value("${curator.connectionTimeoutMs}")
	private int connectionTimeoutMs;

	@Primary
	@Order(0)
	@Bean(initMethod = "start")
	@DependsOn("zookeeperCuratorConfig")
	public CuratorFramework curatorFramework(ZookeeperCuratorConfig zookeeperCuratorConfig) {
		LocalZookeeperCuratorConfig localZookeeperCuratorConfig = (LocalZookeeperCuratorConfig) zookeeperCuratorConfig;
		String connectString = localZookeeperCuratorConfig.decryptString(localZookeeperCuratorConfig.getConnectString());
		return CuratorFrameworkFactory.newClient(connectString, localZookeeperCuratorConfig.getSessionTimeoutMs(), localZookeeperCuratorConfig.getConnectionTimeoutMs(),
				new RetryNTimes(localZookeeperCuratorConfig.getRetryCount(), localZookeeperCuratorConfig.getElapsedTimeMs()));
	}

	public synchronized String decryptString(String encryptedString) {
		String isEncrypt = Config.getInstance().getValue("IsZookeeperEncrypt");
		if (isEncrypt.equalsIgnoreCase("true")) {
			String plainString = encryptedString;
			if (plainString != null && plainString.trim().length() > 0) {
				plainString = SecurityUtil.decryptDes(plainString.trim(), "MeetZookeeper");
			}
			return plainString;
		} else {
			return encryptedString;
		}
	}
}
